package com.adingxiong.cft.util;

import com.adingxiong.cft.config.MinioProperties;
import com.adingxiong.cft.errors.ApiException;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName ImgUtil
 * @Description   图片工具类
 * @Author xiongchao
 * @Date 2021/1/21 13:47
 **/
public class ImgUtil {


    public static void checkType(String fileName ,MinioProperties properties){
        boolean flag = false;
        String suffix = fileName.substring(fileName.lastIndexOf(".") +1);
        for (String str : properties.getFileType()){
            if(suffix.equalsIgnoreCase(str)){
                flag = true;
                break;
            }
        }
        if(!flag){
            throw new ApiException("文件上传格式不支持");
        }
    }

    private static boolean isImage(String fileName) {
        //设置允许上传文件类型
        String suffixList = "jpg,gif,png,ico,bmp,jpeg";
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".")
                + 1, fileName.length());
        if (suffixList.contains(suffix.trim().toLowerCase())) {
            return true;
        }
        return false;
    }



    public static void checkFile(MultipartFile file,MinioProperties properties){
        String fileName = file.getOriginalFilename();
        checkType(fileName,properties);
        if(isImage(fileName)){
            long size = file.getSize();
            if(size > properties.getImgSize()){
                throw new ApiException("图片资源大小超过最大允许:" + properties.getImgSize()/1024/1024 + "M 限制");
            }
        }else {
            throw new ApiException("文件资源大小超过最大允许:" + properties.getFileSize()/1024/1024 + "M 限制");
        }
    }
}
